package com.momo.mal.util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.text.WordUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.impl.cookie.DateParseException;
import org.apache.http.impl.cookie.DateUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import net.momo.mal.R;
import com.momo.mal.database.MalDatabaseAdapter;
import com.momo.mal.entity.Anime;
import com.momo.mal.entity.History;
import com.momo.mal.entity.Related;

public class AnimeUtil {
	public static String parsingWatchedStatus(String status) {
		if (status.equals("watching"))
			return "watching";
		else if (status.equals("completed"))
			return "completed";
		else if (status.equals("on-hold"))
			return "onhold";
		else if (status.equals("dropped"))
			return "dropped";
		else
			return "plantowatch";
	}

	public static String parsingWatchedStatusView(String status) {
		if (status.equals("watching"))
			return "Watching";
		else if (status.equals("completed"))
			return "Completed";
		else if (status.equals("onhold"))
			return "On-hold";
		else if (status.equals("dropped"))
			return "Dropped";
		else
			return "Plan to Watch";
	}

	public static Anime parsingAnimeFromJson(JSONObject json) {
		Anime anime = new Anime();
		int a = 0;
		try {
			anime.setId(json.getString("id"));
			anime.setTitle(json.getString("title"));
			anime.setType(json.getString("type"));
			anime.setStatus(json.getString("status"));
			anime.setEpisode(json.getString("episodes"));
			anime.setClassification(json.getString("classification"));
			anime.setImageUrl(json.getString("image_url"));
			anime.setSynopsis(json.getString("synopsis"));

			anime.setMemberScore(json.getString("members_score"));
			anime.setRank(json.getString("rank"));
			anime.setPopularityRank(json.getString("popularity_rank"));
			anime.setMemberCount(json.getString("members_count"));
			anime.setFavoriteCount(json.getString("favorited_count"));

			anime.setGenre(json.getString("genres").replace("[", "")
					.replace("]", "").replace("\"", "").replace(",", ", "));

			JSONObject jsonObject = json.getJSONObject("other_titles");
			String synonyms = "";
			String english = "";
			String japanese = "";
			if (jsonObject.has("english") == true) {
				english = jsonObject.getString("english").replace("[", "")
						.replace("]", "").replace("\"", "").replace(",", ", ");
			}
			if (jsonObject.has("synonyms") == true) {
				synonyms = jsonObject.getString("synonyms").replace("[", "")
						.replace("]", "").replace("\"", "").replace(",", ", ");
			}
			if (jsonObject.has("japanese") == true) {
				japanese = jsonObject.getString("japanese").replace("[", "")
						.replace("]", "").replace("\"", "").replace(",", ", ");
			}

			anime.setEnglish(english);
			anime.setSynonyms(synonyms);
			anime.setJapanese(japanese);

			List<Related> relations = new ArrayList<Related>();
			Related related = new Related();

			JSONArray jsonArray = json.getJSONArray("manga_adaptations");
			if (jsonArray.length() > 0) {
				for (a = 0; a < jsonArray.length(); a++) {
					anime.setAdaptation("has");
					JSONObject jsonObject2 = jsonArray.getJSONObject(a);

					related = new Related();
					related.setRelatedId(jsonObject2.getString("manga_id"));
					related.setType("adaptations");
					related.setMasterId(json.getString("id"));
					related.setTitle(jsonObject2.getString("title"));
					related.setAnime(1);

					relations.add(related);
				}
			} else {
				anime.setAdaptation("");
			}

			JSONArray jsonArray2 = json.getJSONArray("prequels");
			if (jsonArray2.length() > 0) {
				for (a = 0; a < jsonArray2.length(); a++) {
					anime.setPrequel("has");
					JSONObject jsonObject2 = jsonArray2.getJSONObject(a);

					related = new Related();
					related.setRelatedId(jsonObject2.getString("anime_id"));
					related.setType("prequels");
					related.setMasterId(json.getString("id"));
					related.setTitle(jsonObject2.getString("title"));
					related.setAnime(1);

					relations.add(related);
				}
			} else {
				anime.setPrequel("");
			}

			JSONArray jsonArray3 = json.getJSONArray("sequels");
			if (jsonArray3.length() > 0) {
				for (a = 0; a < jsonArray3.length(); a++) {
					anime.setSequel("has");
					JSONObject jsonObject2 = jsonArray3.getJSONObject(a);

					related = new Related();
					related.setRelatedId(jsonObject2.getString("anime_id"));
					related.setType("sequels");
					related.setMasterId(json.getString("id"));
					related.setTitle(jsonObject2.getString("title"));
					related.setAnime(1);

					relations.add(related);
				}
			} else {
				anime.setSequel("");
			}

			JSONArray jsonArray4 = json.getJSONArray("side_stories");
			if (jsonArray4.length() > 0) {
				for (a = 0; a < jsonArray4.length(); a++) {
					anime.setSideStory("has");
					JSONObject jsonObject2 = jsonArray4.getJSONObject(a);

					related = new Related();
					related.setRelatedId(jsonObject2.getString("anime_id"));
					related.setType("side_stories");
					related.setMasterId(json.getString("id"));
					related.setTitle(jsonObject2.getString("title"));
					related.setAnime(1);

					relations.add(related);
				}
			} else {
				anime.setSideStory("");
			}

			JSONArray jsonArray5 = json.getJSONArray("spin_offs");
			if (jsonArray5.length() > 0) {
				for (a = 0; a < jsonArray5.length(); a++) {
					anime.setSpinOff("has");
					JSONObject jsonObject2 = jsonArray5.getJSONObject(a);

					related = new Related();
					related.setRelatedId(jsonObject2.getString("anime_id"));
					related.setType("spin_offs");
					related.setMasterId(json.getString("id"));
					related.setTitle(jsonObject2.getString("title"));
					related.setAnime(1);

					relations.add(related);
				}
			} else {
				anime.setSpinOff("");
			}

			JSONArray jsonArray6 = json.getJSONArray("alternative_versions");
			if (jsonArray6.length() > 0) {
				for (a = 0; a < jsonArray6.length(); a++) {
					anime.setAlternative("has");
					JSONObject jsonObject2 = jsonArray6.getJSONObject(a);

					related = new Related();
					related.setRelatedId(jsonObject2.getString("anime_id"));
					related.setType("alternative_versions");
					related.setMasterId(json.getString("id"));
					related.setTitle(jsonObject2.getString("title"));
					related.setAnime(1);

					relations.add(related);
				}
			} else {
				anime.setAlternative("");
			}

			anime.setRelations(relations);

			// JSONArray jsonArray = json.getJSONArray("manga_adaptations");
			// StringBuffer adaptation = new StringBuffer(0);
			// for (a = 0; a < jsonArray.length(); a++) {
			// JSONObject jsonObject2 = jsonArray.getJSONObject(a);
			// if (a == 0) {
			// adaptation.append(jsonObject2.getString("title"));
			// } else {
			// adaptation.append(", ").append(
			// jsonObject2.getString("title"));
			// }
			// }
			// anime.setAdaptation(adaptation.toString());
			//
			// StringBuffer prequel = new StringBuffer(0);
			// JSONArray jsonArray2 = json.getJSONArray("prequels");
			// for (a = 0; a < jsonArray2.length(); a++) {
			// JSONObject jsonObject2 = jsonArray2.getJSONObject(a);
			// if (a == 0) {
			// prequel.append(jsonObject2.getString("title"));
			// } else {
			// prequel.append(", ").append(jsonObject2.getString("title"));
			// }
			// }
			// anime.setPrequel(prequel.toString());
			//
			// StringBuffer sequel = new StringBuffer(0);
			// JSONArray jsonArray3 = json.getJSONArray("sequels");
			// for (a = 0; a < jsonArray3.length(); a++) {
			// JSONObject jsonObject2 = jsonArray3.getJSONObject(a);
			// if (a == 0) {
			// sequel.append(jsonObject2.getString("title"));
			// } else {
			// sequel.append(", ").append(jsonObject2.getString("title"));
			// }
			// }
			// anime.setSequel(sequel.toString());
			//
			// StringBuffer sideStory = new StringBuffer();
			// JSONArray jsonArray4 = json.getJSONArray("side_stories");
			// for (a = 0; a < jsonArray4.length(); a++) {
			// JSONObject jsonObject2 = jsonArray4.getJSONObject(a);
			// if (a == 0) {
			// sideStory.append(jsonObject2.getString("title"));
			// } else {
			// sideStory.append(", ").append(
			// jsonObject2.getString("title"));
			// }
			// }
			// anime.setSideStory(sideStory.toString());
			//
			// StringBuffer spinOff = new StringBuffer();
			// JSONArray jsonArray5 = json.getJSONArray("spin_offs");
			// for (a = 0; a < jsonArray5.length(); a++) {
			// JSONObject jsonObject2 = jsonArray5.getJSONObject(a);
			// if (a == 0) {
			// spinOff.append(jsonObject2.getString("title"));
			// } else {
			// spinOff.append(", ").append(jsonObject2.getString("title"));
			// }
			// }
			// anime.setSpinOff(spinOff.toString());
			//
			// StringBuffer alternative = new StringBuffer();
			// JSONArray jsonArray6 = json.getJSONArray("alternative_versions");
			// for (a = 0; a < jsonArray6.length(); a++) {
			// JSONObject jsonObject2 = jsonArray6.getJSONObject(a);
			// if (a == 0) {
			// alternative.append(jsonObject2.getString("title"));
			// } else {
			// alternative.append(", ").append(
			// jsonObject2.getString("title"));
			// }
			// }
			// anime.setAlternative(alternative.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return anime;
	}

	public static void animeAddOrUpdatePopUp(final Anime anime,
			final Context context) {
		MalDatabaseAdapter dbAdapter = new MalDatabaseAdapter(context);
		final boolean status = dbAdapter.hasAnime(anime.getId());

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		LayoutInflater inflater = LayoutInflater.from(context);
		View viewInflate = inflater.inflate(R.layout.dialog_edit_anime, null);
		final Calendar calendar = Calendar.getInstance();

		final Spinner spinnerStatus = (Spinner) viewInflate
				.findViewById(R.id.spinner_status);
		final Spinner spinnerScore = (Spinner) viewInflate
				.findViewById(R.id.spinner_score);
		final Spinner spinnerStartDays = (Spinner) viewInflate
				.findViewById(R.id.spinner_start_days);
		final Spinner spinnerStartMonth = (Spinner) viewInflate
				.findViewById(R.id.spinner_start_month);
		final Spinner spinnerStartYear = (Spinner) viewInflate
				.findViewById(R.id.spinner_start_year);
		final Spinner spinnerFinishDays = (Spinner) viewInflate
				.findViewById(R.id.spinner_finish_days);
		final Spinner spinnerFinishMonth = (Spinner) viewInflate
				.findViewById(R.id.spinner_finish_month);
		final Spinner spinnerFinishYear = (Spinner) viewInflate
				.findViewById(R.id.spinner_finish_year);
		final Spinner spinnerPriority = (Spinner) viewInflate
				.findViewById(R.id.spinner_priority);
		final EditText editEpisode = (EditText) viewInflate
				.findViewById(R.id.edit_episodes);
		final TextView textTitle = (TextView) viewInflate
				.findViewById(R.id.text_title);
		final CheckBox checkBoxUnknownStartDate = (CheckBox) viewInflate
				.findViewById(R.id.checkbox_unknown_date_start_date);
		final CheckBox checkBoxInsertStartDate = (CheckBox) viewInflate
				.findViewById(R.id.checkbox_insert_today_date_start_date);
		final CheckBox checkBoxUnknownFinishDate = (CheckBox) viewInflate
				.findViewById(R.id.checkbox_unknown_date_finish_date);
		final CheckBox checkBoxInsertFinishDate = (CheckBox) viewInflate
				.findViewById(R.id.checkbox_insert_today_date_finish_date);
		final EditText editTags = (EditText) viewInflate
				.findViewById(R.id.edit_tags);
		final EditText editComments = (EditText) viewInflate
				.findViewById(R.id.edit_comments);

		checkBoxUnknownStartDate
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked == true) {
							spinnerStartDays.setEnabled(false);
							spinnerStartDays.setSelection(0);

							spinnerStartMonth.setEnabled(false);
							spinnerStartMonth.setSelection(0);

							spinnerStartYear.setEnabled(false);
							spinnerStartYear.setSelection(0);

							checkBoxInsertStartDate.setChecked(false);

						}
					}
				});

		checkBoxInsertStartDate
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked == true) {
							int day = calendar.get(Calendar.DAY_OF_MONTH);
							int month = calendar.get(Calendar.MONTH);

							spinnerStartDays.setEnabled(true);
							spinnerStartMonth.setEnabled(true);
							spinnerStartYear.setEnabled(true);

							spinnerStartDays.setSelection(day);
							spinnerStartMonth.setSelection(month + 1);
							spinnerStartYear.setSelection(1);

							checkBoxUnknownStartDate.setChecked(false);
						}
					}
				});

		checkBoxUnknownFinishDate
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked == true) {
							spinnerFinishDays.setEnabled(false);
							spinnerFinishDays.setSelection(0);

							spinnerFinishMonth.setEnabled(false);
							spinnerFinishMonth.setSelection(0);

							spinnerFinishYear.setEnabled(false);
							spinnerFinishYear.setSelection(0);

							checkBoxInsertFinishDate.setChecked(false);

						}
					}
				});

		checkBoxInsertFinishDate
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked == true) {
							int day = calendar.get(Calendar.DAY_OF_MONTH);
							int month = calendar.get(Calendar.MONTH);

							spinnerFinishDays.setEnabled(true);
							spinnerFinishMonth.setEnabled(true);
							spinnerFinishYear.setEnabled(true);

							spinnerFinishDays.setSelection(day);
							spinnerFinishMonth.setSelection(month + 1);
							spinnerFinishYear.setSelection(1);

							checkBoxUnknownFinishDate.setChecked(false);
						}
					}
				});

		ArrayAdapter<SpinnerValue> mAdapterYears = new ArrayAdapter<SpinnerValue>(
				context, android.R.layout.simple_spinner_item);
		mAdapterYears
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		int year = calendar.get(Calendar.YEAR);
		mAdapterYears.add(new SpinnerValue("Years", "0"));
		for (int a = 0; a <= 3; a++) {
			mAdapterYears.add(new SpinnerValue(String.valueOf(year - a), String
					.valueOf(year - a)));
		}

		spinnerFinishYear.setAdapter(mAdapterYears);
		spinnerStartYear.setAdapter(mAdapterYears);

		ArrayAdapter<SpinnerValue> mAdapterMonth = new ArrayAdapter<SpinnerValue>(
				context, android.R.layout.simple_spinner_item);
		mAdapterMonth
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		mAdapterMonth.add(new SpinnerValue("Month", "0"));
		mAdapterMonth.add(new SpinnerValue("January", "01"));
		mAdapterMonth.add(new SpinnerValue("Febuary", "02"));
		mAdapterMonth.add(new SpinnerValue("March", "03"));
		mAdapterMonth.add(new SpinnerValue("April", "04"));
		mAdapterMonth.add(new SpinnerValue("May", "05"));
		mAdapterMonth.add(new SpinnerValue("June", "06"));
		mAdapterMonth.add(new SpinnerValue("July", "07"));
		mAdapterMonth.add(new SpinnerValue("August", "08"));
		mAdapterMonth.add(new SpinnerValue("September", "09"));
		mAdapterMonth.add(new SpinnerValue("October", "10"));
		mAdapterMonth.add(new SpinnerValue("November", "11"));
		mAdapterMonth.add(new SpinnerValue("December", "12"));

		spinnerFinishMonth.setAdapter(mAdapterMonth);
		spinnerStartMonth.setAdapter(mAdapterMonth);

		ArrayAdapter<SpinnerValue> mAdapterDays = new ArrayAdapter<SpinnerValue>(
				context, android.R.layout.simple_spinner_item);
		mAdapterDays
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		mAdapterDays.add(new SpinnerValue("Days", "0"));
		for (int a = 1; a <= 9; a++) {
			mAdapterDays.add(new SpinnerValue("0" + String.valueOf(a), "0"
					+ String.valueOf(a)));
		}
		for (int a = 10; a <= days; a++) {
			mAdapterDays.add(new SpinnerValue(String.valueOf(a), String
					.valueOf(a)));
		}

		spinnerFinishDays.setAdapter(mAdapterDays);
		spinnerStartDays.setAdapter(mAdapterDays);

		ArrayAdapter<SpinnerValue> adapterScore = new ArrayAdapter<SpinnerValue>(
				context, android.R.layout.simple_spinner_item);
		adapterScore
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		adapterScore.add(new SpinnerValue("Select score", "0"));
		adapterScore.add(new SpinnerValue("10 - Masterpiece", "10"));
		adapterScore.add(new SpinnerValue("9 - Great", "9"));
		adapterScore.add(new SpinnerValue("8 - Very Good", "8"));
		adapterScore.add(new SpinnerValue("7 - Good", "7"));
		adapterScore.add(new SpinnerValue("6 - Fine", "6"));
		adapterScore.add(new SpinnerValue("5 - Average", "5"));
		adapterScore.add(new SpinnerValue("4 - Bad", "4"));
		adapterScore.add(new SpinnerValue("3 - Very Bad", "3"));
		adapterScore.add(new SpinnerValue("2 - Horrible", "2"));
		adapterScore.add(new SpinnerValue("1 - Appalling", "1"));

		spinnerScore.setAdapter(adapterScore);
		if (anime.getScore() == null || anime.getScore().equalsIgnoreCase("0")) {
			spinnerScore.setSelection(0);
		} else {
			spinnerScore.setSelection(11 - Integer.parseInt(anime.getScore()));
		}

		ArrayAdapter<SpinnerValue> adapterStatus = new ArrayAdapter<SpinnerValue>(
				context, android.R.layout.simple_spinner_item);
		adapterStatus
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		adapterStatus.add(new SpinnerValue("Watching", "watching"));
		adapterStatus.add(new SpinnerValue("Completed", "completed"));
		adapterStatus.add(new SpinnerValue("On-hold", "onhold"));
		adapterStatus.add(new SpinnerValue("Plan to watch", "plantowatch"));
		adapterStatus.add(new SpinnerValue("Dropped", "dropped"));
		
		ArrayAdapter<SpinnerValue> adapterPriority = new ArrayAdapter<SpinnerValue>(
				context, android.R.layout.simple_spinner_item);
		adapterPriority
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		adapterPriority.add(new SpinnerValue("Low", "0"));
		adapterPriority.add(new SpinnerValue("Medium", "1"));
		adapterPriority.add(new SpinnerValue("High", "2"));
		
		spinnerPriority.setAdapter(adapterPriority);

		spinnerStatus.setAdapter(adapterStatus);
		if (anime.getWathcedStatus() != null) {
			if (anime.getWathcedStatus().equalsIgnoreCase("watching")) {
				spinnerStatus.setSelection(0);
			}
			if (anime.getWathcedStatus().equalsIgnoreCase("completed")) {
				spinnerStatus.setSelection(1);
			}
			if (anime.getWathcedStatus().equalsIgnoreCase("onhold")) {
				spinnerStatus.setSelection(2);
			}
			if (anime.getWathcedStatus().equalsIgnoreCase("plantowatch")) {
				spinnerStatus.setSelection(3);
			}
			if (anime.getWathcedStatus().equalsIgnoreCase("dropped")) {
				spinnerStatus.setSelection(4);
			}
		}

		spinnerStatus.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (position == 1) {
					editEpisode.setText(anime.getEpisode());
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		textTitle.setText(anime.getTitle());
		if (anime.getWatchedEpisode() != null) {
			editEpisode.setText(anime.getWatchedEpisode());
		}
		if (anime.getComments() != null) {
			editComments.setText(anime.getComments());
		}
		if (anime.getTags() != null) {
			editTags.setText(anime.getTags());
		}
		
		if(anime.getPriority() != null) {
			spinnerPriority.setSelection(Integer.parseInt(anime.getPriority()));			
		} else {
			spinnerPriority.setSelection(0);
		}

		try {
			Date date = new Date();
			Calendar calendar2 = Calendar.getInstance();
			if (anime.getStartDate() != null
					&& !anime.getStartDate().equals("null")
					&& anime.getStartDate().length() > 0) {
				date = DateUtils.parseDate(anime.getStartDate(),
						new String[] { "MMddyyyy" });
				calendar2.setTime(date);

				spinnerStartDays.setSelection(calendar2.get(Calendar.DATE));
				spinnerStartMonth
						.setSelection(calendar2.get(Calendar.MONTH) + 1);
				int position = (calendar.get(Calendar.YEAR) - calendar2
						.get(Calendar.YEAR)) + 1;
				spinnerStartYear.setSelection(position);
			}

			if (anime.getEndDate() != null
					&& !anime.getEndDate().equals("null")
					&& anime.getEndDate().length() > 0) {
				date = DateUtils.parseDate(anime.getEndDate(),
						new String[] { "MMddyyyy" });
				calendar2.setTime(date);

				spinnerFinishDays.setSelection(calendar2.get(Calendar.DATE));
				spinnerFinishMonth
						.setSelection(calendar2.get(Calendar.MONTH) + 1);
				int position = (calendar.get(Calendar.YEAR) - calendar2
						.get(Calendar.YEAR)) + 1;
				spinnerFinishYear.setSelection(position);
			}
		} catch (DateParseException e) {
			e.printStackTrace();
		}

		// final String animeId = anime.getId();
		builder.setView(viewInflate)
				.setPositiveButton(status == true ? "Update" : "Add",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								// Anime anime = new Anime();
								// anime.setId(animeId);
								anime.setPriority(((SpinnerValue) spinnerPriority
										.getSelectedItem()).getValue());
								anime.setWathcedStatus(((SpinnerValue) spinnerStatus
										.getSelectedItem()).getValue());
								anime.setWatchedEpisode(editEpisode.getText()
										.length() == 0 ? "0" : editEpisode
										.getText().toString());
								anime.setScore(((SpinnerValue) spinnerScore
										.getSelectedItem()).getValue());
								anime.setTags(editTags.getText().toString());
								anime.setComments(editComments.getText()
										.toString());

								if (checkBoxUnknownStartDate.isChecked() == false
										&& spinnerStartMonth
												.getSelectedItemPosition() != 0
										&& spinnerStartDays
												.getSelectedItemPosition() != 0
										&& spinnerStartYear
												.getSelectedItemPosition() != 0) {

									try {
										String month = ((SpinnerValue) spinnerStartMonth
												.getSelectedItem()).getValue();
										String date = ((SpinnerValue) spinnerStartDays
												.getSelectedItem()).getValue();
										String year = ((SpinnerValue) spinnerStartYear
												.getSelectedItem()).getName();

										Date parseDate = DateUtils.parseDate(
												month + date + year,
												new String[] { "MMddyyyy" });

										anime.setStartDate(DateUtils
												.formatDate(parseDate,
														"MMddyyyy"));
									} catch (DateParseException e) {
										anime.setStartDate("null");
										e.printStackTrace();
									}
								} else {
									anime.setStartDate("null");
								}
								if (checkBoxUnknownFinishDate.isChecked() == false
										&& spinnerFinishMonth
												.getSelectedItemPosition() != 0
										&& spinnerFinishDays
												.getSelectedItemPosition() != 0
										&& spinnerFinishYear
												.getSelectedItemPosition() != 0) {

									try {
										String month = ((SpinnerValue) spinnerFinishMonth
												.getSelectedItem()).getValue();
										String date = ((SpinnerValue) spinnerFinishDays
												.getSelectedItem()).getValue();
										String year = ((SpinnerValue) spinnerFinishYear
												.getSelectedItem()).getName();

										Date parseDate = DateUtils.parseDate(
												month + date + year,
												new String[] { "MMddyyyy" });

										anime.setEndDate(DateUtils.formatDate(
												parseDate, "MMddyyyy"));
									} catch (DateParseException e) {
										anime.setEndDate("null");
										e.printStackTrace();
									}
								} else {
									anime.setEndDate("null");
								}

								new AnimeUtil().new RequestAnimeUpdate(context,
										status).execute(anime);
							}
						})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		builder.create();
		builder.show();
	}

	public class RequestAnimeDelete extends AsyncTask<String, Void, Boolean> {
		private ProgressDialog dialog;
		private MalDatabaseAdapter dbAdapter;
		private Context context;

		public RequestAnimeDelete(Context context) {
			dialog = new ProgressDialog(context);
			dbAdapter = new MalDatabaseAdapter(context);
			this.context = context;
		}

		@Override
		protected Boolean doInBackground(String... params) {
			boolean response = false;
			try {
				response = ConnectionUtil
						.postDeleteXML(ConnectionUtil.API_HOST
								+ "api/animelist/delete/" + params[0] + ".xml",
								context);

				if (response == true) {
					dbAdapter.deleteAnime(params[0]);
				}

			} catch (ClientProtocolException e) {
				response = false;
				e.printStackTrace();
			} catch (IOException e) {
				response = false;
				e.printStackTrace();
			}

			return response;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			dialog.dismiss();
			if (result) {
				Toast.makeText(
						context,
						context.getResources().getString(
								R.string.success_remove), Toast.LENGTH_LONG)
						.show();
			} else {
				Toast.makeText(
						context,
						context.getResources()
								.getString(R.string.failed_remove),
						Toast.LENGTH_LONG).show();
			}
		}

		@Override
		protected void onPreExecute() {
			dialog.setMessage("Loading Data ...");
			dialog.show();
		}
	}

	public class RequestAnimeUpdate extends AsyncTask<Anime, Void, Boolean> {
		private ProgressDialog dialog;
		private Context context;
		private MalDatabaseAdapter dbAdapter;
		private boolean status;

		public RequestAnimeUpdate(Context context, boolean status) {
			dialog = new ProgressDialog(context);
			dbAdapter = new MalDatabaseAdapter(context);

			this.context = context;
			this.status = status;
		}

		@Override
		protected Boolean doInBackground(Anime... params) {
			boolean response = false;
			if (status == true) {
				try {
					response = ConnectionUtil.postUpdateXML(params[0], null,
							context, ConnectionUtil.API_HOST_UPDATE_ANIME);
				} catch (IOException e) {
					response = false;
					e.printStackTrace();
				}
			} else {
				try {
					response = ConnectionUtil.postAddXML(params[0], null,
							context, ConnectionUtil.API_HOST_ADD_ANIME);
				} catch (IOException e) {
					response = false;
					e.printStackTrace();
				}
			}

			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss.SSS");
			History history = new History();
			history.setAnimeId(params[0].getId());
			history.setDescription(WordUtils.capitalize(params[0]
					.getWathcedStatus())
					+ " - "
					+ params[0].getWatchedEpisode()
					+ " of "
					+ params[0].getEpisode() + " episodes");
			history.setMangaId("");
			history.setTitle(params[0].getTitle() + " - " + params[0].getType());
			history.setType("anime");
			history.setUpdateDate(format.format(new Date()));

			if (response == true && status == true) {
				dbAdapter.updateAnimeWithPriority(params[0]);
				if (dbAdapter.hasHistory(history) == true) {
					dbAdapter.updateHistory(history);
				} else {
					dbAdapter.insertHistory(history, params[0].getImageUrl());
				}
			}
			if (response == true && status == false) {
				dbAdapter.saveAnime(params[0]);
				dbAdapter.insertHistory(history, params[0].getImageUrl());
			}
			return response;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			dialog.dismiss();
			if (result == true) {
				if (status == true) {
					Toast.makeText(
							context,
							context.getResources().getString(
									R.string.success_update), Toast.LENGTH_LONG)
							.show();
				} else {
					Toast.makeText(
							context,
							context.getResources().getString(
									R.string.success_add), Toast.LENGTH_LONG)
							.show();
				}
			} else {
				if (status == true) {
					Toast.makeText(
							context,
							context.getResources().getString(
									R.string.failed_update), Toast.LENGTH_LONG)
							.show();
				} else {
					Toast.makeText(
							context,
							context.getResources().getString(
									R.string.failed_add), Toast.LENGTH_LONG)
							.show();
				}
			}
		}

		@Override
		protected void onPreExecute() {
			dialog.setMessage("Loading Data ...");
			dialog.show();
		}
	}

}
